<template>
  <div ref="container" />
</template>

<script setup lang="ts">
import type { ILineSeriesData } from '@/types';
import * as echarts from 'echarts';

const props = defineProps({
  category: { type: Array as PropType<string[]>, default: () => [] },
  seriesData: { type: Array as PropType<ILineSeriesData>, default: () => [] },
});

let myChart: echarts.ECharts | undefined;
const container = ref<HTMLDivElement>();
const init = () => {
  myChart = echarts.init(container.value);
};

const setOption = () => {
  const series = props.seriesData.map(item => {
    const obj = { name: '', data: [], type: 'line', smooth: true };
    if ('name' in item) {
      return { ...obj, name: item.name, data: item.data };
    }
    return { ...obj, name: '', data: item };
  });

  const option: echarts.EChartsOption = {
    xAxis: {
      type: 'category',
      data: props.category,
    },
    yAxis: {
      type: 'value',
    },
    legend: { show: true, data: props.seriesData.map(item => ('name' in item ? item.name : '')) },
    tooltip: { show: true, trigger: 'axis' },
    series,
  };

  myChart?.setOption(option);
};

watch([() => props.category, () => props.seriesData], () => {
  setOption();
});

onMounted(() => {
  init();
  setOption();
});
</script>

<style scoped lang="less"></style>
